package vip.denglei.company.controller.app;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Response;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.denglei.company.model.app.AppUserAdoptionRecords;
import vip.denglei.company.model.app.AppUserInfo;
import vip.denglei.company.service.app.AppUserAdoptionRecordsService;
import vip.denglei.company.service.app.AppUserService;
import vip.denglei.company.util.HttpResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 用户认养记录(app_user_adoption_records)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("/appUserAdoptionRecords")
@Slf4j
public class AppUserAdoptionRecordsController {
    /**
     * 服务对象
     */
    @Resource
    private AppUserAdoptionRecordsService appUserAdoptionRecordsService;
    @Resource
    private AppUserService appUserService;

    @Resource
    private WxPayService wxPayService;

    @PostMapping("save/AppUserAdoptionRecords")
    public HttpResult saveAppUserAdoptionRecords(@RequestBody AppUserAdoptionRecords appUserAdoptionRecords, HttpServletRequest request) {
        log.info("AppUserAdoptionRecordsController saveAppUserAdoptionRecords 参数 appUserAdoptionRecords:{}", appUserAdoptionRecords);
        appUserAdoptionRecords.setOrderId(String.valueOf(IdUtil.getSnowflakeNextId()));
        appUserAdoptionRecords.setOrderStatus(0);
        appUserAdoptionRecordsService.save(appUserAdoptionRecords);
        return HttpResult.success(appUserAdoptionRecords);
    }

    @PostMapping("query/getOrderPayInfo")
    public HttpResult getOrderPayInfo(@RequestBody AppUserAdoptionRecords appUserAdoptionRecords, HttpServletRequest request) {
        log.info("AppUserAdoptionRecordsController getOrderPayInfo 参数 appUserOrderBO:{}", appUserAdoptionRecords);

        WxPayUnifiedOrderV3Result.JsapiResult wxPayMpOrderResult = null;
        WxPayUnifiedOrderV3Request wxPayUnifiedOrderV3Request = null;
        if (Objects.nonNull(appUserAdoptionRecords)) {
            LambdaQueryWrapper<AppUserAdoptionRecords> appUserAdoptionRecordsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserAdoptionRecordsLambdaQueryWrapper.eq(AppUserAdoptionRecords::getOrderId, appUserAdoptionRecords.getOrderId());
            AppUserAdoptionRecords queryOrder = appUserAdoptionRecordsService.getOne(appUserAdoptionRecordsLambdaQueryWrapper);
            if (Objects.nonNull(queryOrder)) {
                if (queryOrder.getPaymentStatus().equals(1)) {
                    return HttpResult.err("该订单已经支付，请勿重复支付");
                }
                queryOrder.setOutTradeNo("wx" + IdUtil.getSnowflakeNextId());
                appUserAdoptionRecordsService.updateById(queryOrder);
                LambdaQueryWrapper<AppUserInfo> appUserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appUserInfoLambdaQueryWrapper.eq(AppUserInfo::getUserId, queryOrder.getUserId());
                AppUserInfo appUserInfo = appUserService.getOne(appUserInfoLambdaQueryWrapper);
                if (Objects.nonNull(appUserInfo)) {
                    wxPayUnifiedOrderV3Request = new WxPayUnifiedOrderV3Request();
                    //调起支付的人的 openId
                    WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
                    payer.setOpenid(appUserInfo.getWechatId());
                    wxPayUnifiedOrderV3Request.setPayer(payer);
                    //订单编号
                    wxPayUnifiedOrderV3Request.setOutTradeNo(queryOrder.getOutTradeNo());
                    //订单金额
                    wxPayUnifiedOrderV3Request.setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(queryOrder.getProTotal()));
                    //商品描述
                    wxPayUnifiedOrderV3Request.setDescription("description");
                    //回调的 URL 地址
                    wxPayUnifiedOrderV3Request.setNotifyUrl("https://hbcaiyu.cn/company/appUserAdoptionRecords/weChatPayNotify");
                    try {
                        wxPayMpOrderResult = wxPayService.createOrderV3(TradeTypeEnum.JSAPI, wxPayUnifiedOrderV3Request);
                    } catch (WxPayException e) {
                        throw new RuntimeException(e);
                    }
                    log.info("微信调用返回wxPayUnifiedOrderResult{}:", wxPayMpOrderResult);

                }

            }
        }

        return HttpResult.success(wxPayMpOrderResult);
    }

    @PostMapping(value = "/weChatPayNotify")
    public String weChatPayNotify(@RequestBody String notifyData, HttpServletRequest request) {
        log.info("AppUserAdoptionRecordsController weChatPayNotify 参数 notifyData:{}", notifyData);

        try {
            WxPayNotifyV3Result wxPayNotifyV3Result = wxPayService.parseOrderNotifyV3Result(notifyData, null);
            log.info("支付结果回调解析 参数 wxPayNotifyV3Result:{}", wxPayNotifyV3Result);
            LambdaQueryWrapper<AppUserAdoptionRecords> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserOrderLambdaQueryWrapper.eq(AppUserAdoptionRecords::getOutTradeNo, wxPayNotifyV3Result.getResult().getOutTradeNo());
            AppUserAdoptionRecords adoptionRecords = appUserAdoptionRecordsService.getOne(appUserOrderLambdaQueryWrapper);
            if (Objects.nonNull(adoptionRecords)) {
                adoptionRecords.setPaymentStatus(1);
                adoptionRecords.setOrderStatus(1);
                adoptionRecords.setPaymentTime(DateUtil.date());
                appUserAdoptionRecordsService.updateById(adoptionRecords);
                return WxPayNotifyV3Response.success("微信支付回调成功");
            }
        } catch (WxPayException e) {
            throw new RuntimeException(e);
        }
        return WxPayNotifyV3Response.fail("微信支付回调成功");
    }


}
